package greedy;

import java.util.*;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/28 22:32
 * https://leetcode-cn.com/problems/merge-intervals/
 */
public class Merge {

    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] a, int[] b) {
                return Integer.compare(a[0], b[0]);
            }
        });
        LinkedList<int[]> list =new LinkedList<>();
        int start = intervals[0][0];
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] > intervals[i - 1][1]) {
                list.add(new int[]{start, intervals[i - 1][1]});
                start = intervals[i][0];
            } else {
                //重合
                intervals[i][1] = Math.max(intervals[i - 1][1], intervals[i][1]);
            }
        }
        list.add(new int[]{start, intervals[intervals.length - 1][1]});
        return list.toArray(new int[list.size()][]);
    }

    public int[][] merge1(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] a, int[] b) {
                return Integer.compare(a[0], b[0]);
            }
        });
        LinkedList<int[]> list =new LinkedList<>();
        list.add(intervals[0]);
        for (int i = 1; i < intervals.length; i++) {
            //重合
            if (intervals[i][0] <= list.getLast()[1]) {
                int start = list.getLast()[0];
                int end = Math.max(list.getLast()[1], intervals[i][1]);
                list.removeLast();
                list.add(new int[]{start, end});
            } else {
                list.add(intervals[i]);
            }
        }
        return list.toArray(new int[list.size()][]);
    }

    public static void main(String[] args) {

    }
}
